package com.jyxd.web.task;

import com.jyxd.web.data.basic.CommonSetting;
import com.jyxd.web.data.basic.QuartzTask;
import com.jyxd.web.service.assessment.basic.CommonSettingService;
import com.jyxd.web.service.assessment.basic.QuartzTaskService;
import com.jyxd.web.util.CronUtil;
import com.jyxd.web.util.UUIDUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 任务调度处理
 */
@Configuration
public class QuartzSchedulerUtil {

    private static Logger logger = LoggerFactory.getLogger(QuartzSchedulerUtil.class);

    /*// 任务调度
    @Autowired
    private Scheduler scheduler;*/

    @Autowired
    private QuartzTaskService quartzTaskService;
    @Autowired
    private CommonSettingService commonSettingService;

    /**
     * 开始执行所有任务
     *
     * @throws SchedulerException
     */
    public void startJob(Scheduler scheduler) throws SchedulerException {
        logger.info("scheduler:" + scheduler.toString());
        startVitalSignsJob(scheduler);
        deleteMonitorLifeDataJob(scheduler);//自动删除监护仪历史数据
        //medOrderBackupsJob(scheduler);
        YBListJob(scheduler);//同步HIS医保数据
        startHISQualityControlJob(scheduler);//两小时同步患者信息
        startCrrtNurseJob(scheduler);
        scheduler.start();
    }
    /**
     * 医嘱数据分表定时任务
     *
     * @param scheduler
     */
    private void medOrderBackupsJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(MedOrderBackupsJob.class).withIdentity("MedOrderBackupsJob", "MedOrderBackupsJob").build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 0 * * ? ");//每天晚上凌晨00点运行
        Map<String, Object> map = new HashMap<>();
        map.put("jobName", "MedOrderBackupsJob");
        map.put("jobGroup", "MedOrderBackupsJob");
        QuartzTask quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
        if (quartzTask == null) {
            //如果为空 说明数据库中没有这个任务 需要添加
            QuartzTask data = new QuartzTask();
            data.setId(UUIDUtil.getUUID());
            data.setCreateTime(new Date());
            data.setCron("0 0 0 * * ? ");
            data.setDescription("医嘱数据分表定时任务");
            data.setJobGroup("MedOrderBackupsJob");
            data.setJobName("MedOrderBackupsJob");
            data.setStatus(1);
            data.setTaskName("MedOrderBackupsJob");
            data.setType("系统任务");
            quartzTaskService.insert(data);
        } else if (quartzTask.getStatus() == 1) {
            //转态 1: 正常执行
            cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getCron());
        } else {
            return;
        }
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("MedOrderBackupsJob", "MedOrderBackupsJob")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * HIS医保数据对接
     *
     * @param scheduler
     */
    private void YBListJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(YBJob.class).withIdentity("YBJob", "YBJob").build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("* * 0/1 * * ? *");//每5分钟一次
        Map<String, Object> map = new HashMap<>();
        map.put("jobName", "YBJob");
        map.put("jobGroup", "YBJob");
        QuartzTask quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
        if (quartzTask == null) {
            //如果为空 说明数据库中没有这个任务 需要添加
            QuartzTask data = new QuartzTask();
            data.setId(UUIDUtil.getUUID());
            data.setCreateTime(new Date());
            data.setCron("* * 0/1 * * ? *");//每小时一次
            data.setDescription("同步HIS医保任务");
            data.setJobGroup("YBJob");
            data.setJobName("YBJob");
            data.setStatus(1);
            data.setTaskName("YBJob");
            data.setType("系统任务");
            quartzTaskService.insert(data);
        } else if (quartzTask.getStatus() == 1) {
            //转态 1: 正常执行
            cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getCron());
        } else {
            return;
        }
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("YBJob", "YBJob")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 获取Job信息
     *
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(String name, String group, Scheduler scheduler) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改某个任务的执行时间
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(String name, String group, String time, Scheduler scheduler) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }

    /**
     * 立即执行某个任务
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean beginJob(String name, String group, String time, Scheduler scheduler) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                .withSchedule(cronScheduleBuilder).build();
        date = scheduler.rescheduleJob(triggerKey, trigger);
        return date != null;
    }

    /**
     * 暂停所有任务
     *
     * @throws SchedulerException
     */
    public void pauseAllJob(Scheduler scheduler) throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暂停某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name, String group, Scheduler scheduler) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        System.out.println(jobKey.toString());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复所有任务
     *
     * @throws SchedulerException
     */
    public void resumeAllJob(Scheduler scheduler) throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢复某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void resumeJob(String name, String group, Scheduler scheduler) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name, String group, Scheduler scheduler) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

    /**
     * 动态修改任务执行时间
     *
     * @return
     * @throws Exception
     */
    public String trigger(String name, String group, Scheduler scheduler) throws Exception {
        // 获取任务
        JobKey jobKey = new JobKey(name, group);
        System.out.println("jobKey:" + jobKey);
        // 获取 jobDetail
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        System.out.println("jobDetail:" + jobDetail);
        // 生成 trigger
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?"))
                .build();
        // 删除任务，不删除会报错。报任务已存在
        scheduler.deleteJob(jobKey);
        // 启动任务
        scheduler.scheduleJob(jobDetail, trigger);
        return "trigger";
    }

    /**
     * 动态关闭任务
     *
     * @return
     * @throws Exception
     */
    public String pause(String name, String group, Scheduler scheduler) throws Exception {
        JobKey key = new JobKey(name, group);
        scheduler.pauseJob(key);
        return "pause";
    }

    /**
     * 动态启动任务
     *
     * @return
     * @throws Exception
     */
    public void start(String name, String group, Scheduler scheduler) throws Exception {
        JobKey key = new JobKey(name, group);
        scheduler.resumeJob(key);
    }
    /**
     * 自动删除七天之前的数据
     *
     * @param scheduler
     */
    private void deleteMonitorLifeDataJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(DeleteMonitorLifeDataJob.class).withIdentity("MonitorLifeDataJob", "MonitorLifeDataJob").build();
        // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        // 基于表达式构建触发器
        Map<String, Object> map = new HashMap<>();
        map.put("jobName", "MonitorLifeDataJob");
        map.put("jobGroup", "MonitorLifeDataJob");
        QuartzTask quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
        if (Objects.isNull(quartzTask)) {
            logger.error("需要执行的MonitorLifeDataJob任务不存在");
            return;
        }
        String cron = quartzTask.getCron();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("MonitorLifeDataJob", "MonitorLifeDataJob")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    // 自动同步生命体征任务
    private void startVitalSignsJob(Scheduler scheduler) throws SchedulerException {
        Map map = new HashMap();
        map.put("settingType", "synLifeType");
        List<CommonSetting> commonSettingList = commonSettingService.getCommonSettingByType(map);
        if (!CollectionUtils.isEmpty(commonSettingList)) {
            if (commonSettingList.get(0).getOnOff().equals("0") && commonSettingList.get(0).getSettingContent() != "") {

                // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
                // JobDetail 是具体Job实例
                JobDetail jobDetail = JobBuilder.newJob(VitalSignsJob.class).withIdentity("VitalSignsJob", "VitalSignsJob").build();
                // 基于表达式构建触发器
                String cron = CronUtil.createLoopCronExpression(1, Integer.valueOf(commonSettingList.get(0).getSettingContent()));
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                // CronTrigger表达式触发器 继承于Trigger
                // TriggerBuilder 用于构建触发器实例
                CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("VitalSignsJob", "VitalSignsJob")
                        .withSchedule(cronScheduleBuilder).build();
                scheduler.scheduleJob(jobDetail, cronTrigger);
            } else {
                System.out.println("定时任务关闭状态");
            }
        } else {
            System.out.println("数据库中无此任务设置数据");
        }
    }

    /**
     * 定时更新His患者质控指标数据
     *
     * @param scheduler
     */
    private void startHISQualityControlJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(HISQualityControlJob.class).withIdentity("HISQualityControlJob", "HISQualityControlJob").build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("* * 0/2 * * ? *");//每2小时一次
        Map<String, Object> map = new HashMap<>();
        map.put("jobName", "HISQualityControlJob");
        map.put("jobGroup", "HISQualityControlJob");
        QuartzTask quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
        if (quartzTask == null) {
            //如果为空 说明数据库中没有这个任务 需要添加
            QuartzTask data = new QuartzTask();
            data.setId(UUIDUtil.getUUID());
            data.setCreateTime(new Date());
            data.setCron("* * 0/2 * * ? *");//每2小时一次
            data.setDescription("同步His患者质控指标数据任务");
            data.setJobGroup("HISQualityControlJob");
            data.setJobName("HISQualityControlJob");
            data.setStatus(1);
            data.setTaskName("HISQualityControlJob");
            data.setType("系统任务");
            quartzTaskService.insert(data);
        } else if (quartzTask.getStatus() == 1) {
            //转态 1: 正常执行
            cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getCron());
        } else {
            return;
        }
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("HISQualityControlJob", "HISQualityControlJob")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 定时更新His患者旧的生命
     *
     * @param scheduler
     */
    private void startOldPatientDataJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(OldPatientDataJob.class).withIdentity("OldPatientDataJob", "OldPatientDataJob").build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("* * 0/3 * * ? *");//每2小时一次
        Map<String, Object> map = new HashMap<>();
        map.put("jobName", "OldPatientDataJob");
        map.put("jobGroup", "OldPatientDataJob");
        QuartzTask quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
        if (quartzTask == null) {
            //如果为空 说明数据库中没有这个任务 需要添加
            QuartzTask data = new QuartzTask();
            data.setId(UUIDUtil.getUUID());
            data.setCreateTime(new Date());
            data.setCron("* * 0/3 * * ? *");//每5分钟一次
            data.setDescription("同步His患者的生命体征数据任务");
            data.setJobGroup("OldPatientDataJob");
            data.setJobName("OldPatientDataJob");
            data.setStatus(1);
            data.setTaskName("OldPatientDataJob");
            data.setType("系统任务");
            quartzTaskService.insert(data);
        } else if (quartzTask.getStatus() == 1) {
            //转态 1: 正常执行
            cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getCron());
        } else {
            return;
        }
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("OldPatientDataJob", "OldPatientDataJob")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
    /**
     * 定时更新His患者旧的生命
     *
     * @param scheduler
     */
    private void startNewPatientDataJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(OldPatientDataJob.class).withIdentity("NewPatientDataJob", "NewPatientDataJob").build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("* * 0/3 * * ? *");//每2小时一次
        Map<String, Object> map = new HashMap<>();
        map.put("jobName", "NewPatientDataJob");
        map.put("jobGroup", "NewPatientDataJob");
        QuartzTask quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
        if (quartzTask == null) {
            //如果为空 说明数据库中没有这个任务 需要添加
            QuartzTask data = new QuartzTask();
            data.setId(UUIDUtil.getUUID());
            data.setCreateTime(new Date());
            data.setCron("* * 0/3 * * ? *");//每5分钟一次
            data.setDescription("同步His患者的新的生命体征数据任务");
            data.setJobGroup("NewPatientDataJob");
            data.setJobName("NewPatientDataJob");
            data.setStatus(1);
            data.setTaskName("NewPatientDataJob");
            data.setType("系统任务");
            quartzTaskService.insert(data);
        } else if (quartzTask.getStatus() == 1) {
            //转态 1: 正常执行
            cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getCron());
        } else {
            return;
        }
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("OldPatientDataJob", "OldPatientDataJob")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    private void startCrrtNurseJob(Scheduler scheduler) throws SchedulerException {
        Map map = new HashMap();
        map.put("settingType", "synCrrtNurse");
        List<CommonSetting> commonSettingList = commonSettingService.getCommonSettingByType(map);
        if (!CollectionUtils.isEmpty(commonSettingList)) {
            if (commonSettingList.get(0).getOnOff().equals("0") && commonSettingList.get(0).getSettingContent() != "") {

                // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
                // JobDetail 是具体Job实例
                JobDetail jobDetail = JobBuilder.newJob(CrrtNurseJob.class).withIdentity("CrrtNurseJob", "CrrtNurseJob").build();
                // 基于表达式构建触发器
                String cron = CronUtil.createLoopCronExpression(1, Integer.valueOf(commonSettingList.get(0).getSettingContent()));
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                // CronTrigger表达式触发器 继承于Trigger
                // TriggerBuilder 用于构建触发器实例
                CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("CrrtNurseJob", "CrrtNurseJob")
                        .withSchedule(cronScheduleBuilder).build();
                scheduler.scheduleJob(jobDetail, cronTrigger);
            } else {
                System.out.println("定时任务关闭状态");
            }
        } else {
            System.out.println("数据库中无此任务设置数据");
        }
    }
}
